/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */

package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.StringPropertySelectionModel;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.IPage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.IContactService;
import com.crm.model.User;
import com.crm.model.Contact;

import java.util.List;

/**
 * @author <a href="mailto:huang.huang@hingesoftware.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class CustomerSelect extends BasePage implements PageBeginRenderListener{

    private static Log log = LogFactory.getLog(CustomerSelect.class);
    private int count;

    @InjectSpring("contactService")
    public abstract IContactService getContactService();

    @InjectState("userSession")
    public abstract User getUserSession();

    @InjectPage("ProcessInfo")
    public abstract ProcessInfo getProcessInfoPage();

    public abstract String getKeyword();
    public abstract String getFieldSearch();

    public String getRecordCount() {
        return "共" + count + "条记录";
    }

    public void pageBeginRender(PageEvent event){
        if(getUserSession().getUserCode()==null)
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
    }

    public IPropertySelectionModel getFieldSearchModel(){
        return new StringPropertySelectionModel(new String[]{"联系人","所属客户","职位"});

    }

    public List getEntries(){
        try{
            String keyword = getKeyword() == null ? getKeyword() : getKeyword().trim();
            List list = getContactService().getContacts(getUserSession(),new String[]{keyword, getFieldSearch()});
            count = list.size();
            return list;
        }
        catch(Exception e){
            log.warn(getUserSession().getUsername()
                    + " : The exception happened when search customer info! Message:"
                    + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public void searchByKeyword(){
    }

    public IPage onShowDetails(Contact contact) {
        ProcessInfo page = getProcessInfoPage();
        page.setContactInfo(contact);
        return page;
    }    

}
